Conditions
If
The if keyword is used to make conditional statements. Just like the word in the English language, if a condition is true, then something happens. Let’s take a look at this code snippet
local x = 10;
if (x > 5) {
print("Bigger than 5")
}
// Output: Bigger than 5
Elseif
If statements can be chained together with the elseif keyword. These are executed sequentially
local x = 5;
if (x > 10) {
print("Bigger than 10")
} elseif (x > 5) {
print("Bigger than 5")
} else if (x > 0) {
print("Bigger than 0")
}
// Output: Bigger than 0
Else
The else keyword if another conditional statement. The else statement will only execute if the if or elseif conditions were not met.
local x = 0;
if (x > 0) {
print("Positive")
} elseif (x < 0) {
print("Negative")
} else {
print("Zero")
}
// Output: Zero
Switch
A switch statement is useful when you want to compare a single value against many possible options. Instead of writing a long chain of if and elseif checks, a switch lets you organize the conditions more clearly and makes your code easier to read.
local weather = "Rain"
switch (weather) {
case "Sunny":
print("Wear sunglasses.")
break;
case "Rain":
print("Take an umbrella.")
break;
case "Snow":
print("Wear a warm coat.")
break;
default:
print("Check the forecast.")
break;
}
// Output: Take an umbrella
As seen in the example, the switch also has some extra keywords available
| Keyword | Description |
|---|---|
case |
Possible value to compare against |
break |
Stops the switch after a matching case runs |
default |
Runs if no case matches |
Ternary conditional operator
The ternary conditional operator ?: is a short way to write a simple if-else expression. It checks a condition:
- If the condition is
true, it returns the first value - If the condition is
false, it returns the second value
local age = 17;
local access = age >= 18 ? "Allowed" : "Denied"; // Denied
// Without the ternary condition you would have
local age = 17;
local access;
if (age >= 18) {
access = true;
} else {
access = false;
}
Use the ternary operator when you want to keep simple conditions short and readable.